﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;

namespace System
{
    /// <summary>
    /// 工具类
    /// </summary>
    public partial class Utils
    {
        public static string AppName = "Agile";
        /// <summary>
        /// 文件提供程序
        /// </summary>
        public static IAgileFileProvider DefaultFileProvider { get; internal set; }
        public static string ContentRootPath { get; set; }

        #region 对象转换To
        public static T GetObjTranNull<T>(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return (T)System.Convert.ChangeType("", typeof(T));
                }
                else
                {
                    if (obj.GetType() == typeof(T))
                        return (T)obj;
                }
                return (T)System.Convert.ChangeType(obj, typeof(T));
            }
            catch
            { }
            return default(T);
        }
        public static T To<T>(object value)
        {
            return (T)To(value, typeof(T));
        }
        public static object To(object value, Type destinationType)
        {
            return To(value, destinationType, CultureInfo.InvariantCulture);
        }
        public static object To(object value, Type destinationType, CultureInfo culture)
        {
            if (value == null)
                return null;

            var sourceType = value.GetType();

            var destinationConverter = TypeDescriptor.GetConverter(destinationType);
            if (destinationConverter.CanConvertFrom(value.GetType()))
                return destinationConverter.ConvertFrom(null, culture, value);

            var sourceConverter = TypeDescriptor.GetConverter(sourceType);
            if (sourceConverter.CanConvertTo(destinationType))
                return sourceConverter.ConvertTo(null, culture, value, destinationType);

            if (destinationType.IsEnum && value is int)
                return Enum.ToObject(destinationType, (int)value);

            if (!destinationType.IsInstanceOfType(value))
                return Convert.ChangeType(value, destinationType, culture);

            return value;
        }
        #endregion
    }
}
